import { Button, Card, Form, Checkbox, Select, Input, DatePicker, message } from 'antd';
import { useEffect, useState } from 'react';
import moment from 'moment';
import {
  getusrTuitionInfo,
  putusrTuitionInfo,
} from '@/services/baseinfo';

const NewMessage: React.FC = (props: any) => {
  const [form] = Form.useForm();
  const [componentDisabled, setComponentDisabled] = useState<boolean>(true);
  const [userInfo, setUserInfo] = useState(null);

  const initialValues = {
    isPaidTuition: userInfo?.isPaidTuition,
    unpaidReason: userInfo?.unpaidReason,
  };

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const response = await getusrTuitionInfo(null, null);
      if (response && response.result) {
        setUserInfo(response.result);
      }
    } catch (error) {
      console.error('Error fetching user info:', error);
    }
  };

  const onFinish = (values: any) => {
    putusrTuitionInfo(null, values)
      .then((response) => {
        console.log('API response:', response.code);
        if (response?.code == '200') {
          message.success('提交成功');
        } else message.error('提交失败');
      })
      .catch((error) => {
        console.error('API error:', error);
      });
  };

  const onReset = () => {
    form.resetFields();
  };

  if (userInfo === null || userInfo === undefined) {
    return <p>Loading...</p>;
  }

  return (
    <Card>
      <Checkbox
        checked={componentDisabled}
        onChange={(e) => setComponentDisabled(e.target.checked)}
      >
        信息有错?点击更改!
      </Checkbox>
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 10 }}
        form={form}
        disabled={componentDisabled}
        initialValues={initialValues}
        name="control-hooks"
        onFinish={onFinish}
        style={{ maxWidth: 800 }}
      >
        <Form.Item name="isPaidTuition" label="是否已交学费" rules={[{ required: true }]}>
          <Select >
            <Select.Option value="1">是</Select.Option>
            <Select.Option value="0">否</Select.Option>
          </Select>
        </Form.Item>
        {(userInfo?.isPaidTuition === "0") && ( // 根据 "是否已交学费" 字段的值来条件渲染 "未交学费原因" 字段
          <Form.Item
            name="unpaidReason"
            label="未交学费原因"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
        )}
        <Form.Item>
          <Button type="primary" htmlType="submit" style={{ marginLeft: 150, width: 150 }}>
            确定更改
          </Button>
          <Button
            htmlType="button"
            onClick={onReset}
            style={{ marginLeft: 150, marginTop: 20, width: 150 }}
          >
            放弃修改
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default NewMessage;
